package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.admin.dto.LoginDto;
import com.heima.admin.entity.AdUser;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.IAdUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.AppJwtUtil;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 管理员用户信息表 服务实现类
 * </p>
 *
 * @author gxm
 * @since 2023-12-17
 */
@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements IAdUserService {

    @Override
    public ResponseResult login(LoginDto dto) {

        //1.根据用户名查询,不存在就返回提示
        LambdaQueryWrapper<AdUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AdUser::getName, dto.getName());
        AdUser adUser = this.getOne(queryWrapper);
        if (adUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.USER_NOT_EXIST);
        }

        //2. 密码比对,如果错误就返回提示
        String pass = DigestUtils.md5Hex(dto.getPassword() + adUser.getSalt());//前端密码加密
        if (!StringUtils.equals(adUser.getPassword(), pass)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }

        //3. 生成token
        Map<String, Object> claimMaps = new HashMap<>();
        claimMaps.put("userId", adUser.getId());
        claimMaps.put("name", adUser.getName());
        String token = AppJwtUtil.getToken(claimMaps);

        //4. 组装结果返回
        Map resultMap = new HashMap();
        adUser.setPassword("");
        adUser.setSalt("");
        adUser.setPhone("");
        resultMap.put("user", adUser);
        resultMap.put("token", token);
        return ResponseResult.okResult(resultMap);
    }
}
